JavaScript Form Validation

1. Basic Form Validation

Ensure that fields are filled and provide basic feedback if fields are empty or invalid.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <form onsubmit="event.preventDefault(); validateBasicForm();" class="row g-3 needs-validation" >
            <div class="col-md-6" >
                <label for="basicUsername" class="form-label" >Username </label >
                <input type="text" id="basicUsername" class="form-control" required >
            </div >
            <div class="col-md-6" >
                <label for="basicEmail" class="form-label" >Email </label >
                <input type="email" id="basicEmail" class="form-control" required >
            </div>
            <div class="col-12" >
                <button class="btn btn-primary" type="submit" >Submit </button >
            </div>
         </form>
    </div>
    <Script>
        function validateBasicForm() {
            let username = document.getElementById("basicUsername").value;
            let email = document.getElementById("basicEmail").value;
            if (!username) alert("Username cannot be empty");
            else if (!email.match(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)) alert("Invalid email address");
            else alert("Form submitted successfully!");
        }
    </Script>
</body>
</html>
             

2. Advanced Form Validation

Real-time feedback using event listeners to validate email as the user types.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div >
                    
        <class="col-md-12" >
        <label for="advEmail" class="form-label">Email </label >
                    
    </div >
    <div class="col-md-6" >
        <label for="basicEmail" class="form-label" >Email </label >
        <input type="email" id="advEmail" class="form-control">
        <small id="emailMessage" class="text-danger"> </small >
    </div>
    <Script>
        document.getElementById("advEmail").addEventListener("input", function() {
            let email = this.value;
            let message = document.getElementById("emailMessage");
            if (!email.match(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/)) message.textContent = "Invalid email format";
            else message.textContent = "";
        });
    </Script>
</body>
</html>
               

3. Dynamic Form Validation

Change validation rules dynamically based on selected options.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="col-md-6" >
        <label for="userType" class="form-label">User Type </label >
        <select id="userType" class="form-select">
            <option value="Regular">Regular </option >
            <option value="VIP"> VIP </option>
        </select>
    </div>
    <div class="col-md-6">
        <label for="phoneNumber" class="form-label">Phone Number </label >
        <label for="userType" class="form-label">User Type </label >
        <input type="tel" id="phoneNumber" class="form-control" >
    </div>
    <Script>
        document.getElementById("userType").addEventListener("change", function() {
            let phoneNumber = document.getElementById("phoneNumber");
            if (this.value === "VIP") phoneNumber.setAttribute("required", "required");
            else phoneNumber.removeAttribute("required");
        });
    </Script>
</body>
</html>
        

4. Password Strength Validation

Check password strength as the user types.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <form class="row g-3 needs-validation">
            <div class="col-md-12">
                <label for="password" class="form-label">Password </label >
                <input type="password" id="password" class="form-control" </label >
                <id="strength" class="text-info"></small >
            </div>
     </div>
     <Script>
        document.getElementById("password").addEventListener("input", function() {
            let strength = document.getElementById("strength");
            let value = this.value;
            if (value.length > 8 && /[A-Z]/.test(value) && /[0-9]/.test(value)) strength.textContent = "Strong";
            else if (value.length > 5) strength.textContent = "Medium";
            else strength.textContent = "Weak";
        });
    </Script>
</body>
</html>
                

5. Dynamic Dropdowns

Populate a city dropdown based on the selected country.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div>
        <form class="row g-3 needs-validation">
            <div class="col-md-6">
                <label for="country" class="form-label">Country </label >
                <select id="country" class="form-select" onchange="populateCities()" >
                    <option value="USA">USA</option>
                    <option value="Canada">Canada</option>
                </select>
            </div>
            <div class="col-md-6">
                <label for="city" class="form-label">City</label>
                <select id="city" class="form-select"></select>
            </div>
            <Script>
                function populateCities() {
                    let country = document.getElementById("country").value;
                    let cityDropdown = document.getElementById("city");
                    cityDropdown.innerHTML = ""; // Clear current options
                    let cities = {
                        USA: ["New York", "Los Angeles", "Chicago"],
                        Canada: ["Toronto", "Vancouver", "Montreal"]
                    };
                    cities[country].forEach(city => {
                    let option = document.createElement("option");
                    option.textContent = city;
                    cityDropdown.appendChild(option);
                    });
                }
    </Script>
</body>
</html>